package com.seqb.manage.reptile.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seqb.manage.video.dao.VideoDao;
import com.seqb.manage.video.domain.VideoDO;
import com.seqb.utils.AesUtils;
import com.seqb.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2021/4/1
 */
@Service
public class HxcVideoServiceImpl {

    @Autowired
    private VideoDao videoDao;
    @Autowired
    private RestTemplate restTemplate;

    public void reptileHxcVideo() {
        //先删除原来数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", "2");
        videoDao.delete(queryWrapper);

        ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 20,
                60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        for (int k = 1; k < 100000; k++) {
            //{"clientType":4,"length":10,"page":1,"searchText":"","type":2,"orderText":[{"dir":"desc","column":"addTimeStamp"}]}
            //请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("clientType", 4);
            params.put("length", 10);
            params.put("page", k);
            params.put("type", "2");

            System.out.println("第"+k+"次请求");

            //视频列表api
            String requestUrl = "https://www.371zhongyi.com/video/getList";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpMethod httpMethod = HttpMethod.POST;
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("endata", AesUtils.encrypt(JsonUtils.beanToJson(params)));
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            if (null == responseEntity) {
                continue;
            }
            HttpStatus status = responseEntity.getStatusCode();
            List videoList = null;
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                JSONObject entityObject = JSONObject.parseObject(entityBody);
                String endata = entityObject.getString("endata");
                String result = AesUtils.decrypt(endata);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = jsonObject.getString("code");
                if ("1".equals(code)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    Long recordsTotal = data.getLong("recordsTotal");
                    //System.out.println("爬取到的视频总数：" + recordsTotal);
                    videoList = data.getJSONArray("list");
                }
            }
            if (null == videoList || videoList.size() <= 0) {
                return;
            }
            for (int i = 0; i < videoList.size(); i++) {
                JSONObject video = (JSONObject) videoList.get(i);
                Long id = video.getLong("id");
                String name = video.getString("name").replace(" ", "");

                //下载视频线程
                tpe.execute(new SaveVideo(id, name));
            }
        }

        //关闭线程池
        tpe.shutdown();
    }

    /**
     * 保存视频线程
     */
    class SaveVideo implements Runnable {
        Long id;
        String name;

        public SaveVideo(Long id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public void run() {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpMethod httpMethod = HttpMethod.POST;

            //视频路径
            String requestUrl = "https://www.371zhongyi.com/video/getUrl";
            //请求参数
            // {"clientType":4,"videoId":"23890"}
            Map params = new HashMap<>();
            params.put("clientType", 4);
            params.put("videoId", id);
            Map paramsMap = new HashMap<>();
            paramsMap.put("endata", AesUtils.encrypt(JsonUtils.beanToJson(params)));
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = null;
            try {
                responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            if (null == responseEntity) {
                return;
            }
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                JSONObject entityObject = JSONObject.parseObject(entityBody);
                String endata = entityObject.getString("endata");
                String result = AesUtils.decrypt(endata);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = jsonObject.getString("code");
                if ("1".equals(code)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    String url = data.getString("url");
                    System.out.println("视频ID：" + id + "，视频名称：" + name + "，视频路径：" + url);
                    //生成一条记录
                    VideoDO saveDO = new VideoDO();
                    saveDO.setId(id);
                    saveDO.setType("2");
                    saveDO.setFileUrl(url);
                    saveDO.setName(name);
                    videoDao.insert(saveDO);
                }
            }
        }
    }

}
